package com.news.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.news.bean.Link;
import com.news.dao.linkDao;
import com.news.util.DButil;

public class LinkDaoImpl implements linkDao{
	private final String ADDLINK = "insert into link(name,address,img_logo,sort) values(?,?,?,?)";
	private final String DELLINK = "delete from link where id=?";
	private final String EDITLINK = "update link set name=?, address=?, sort=? where id=?";
	private final String LINKLIST = "select * from link";
	public List<Link> getlinkList(Map<?,?> map) {

		List<Link> list = new ArrayList<Link>();
		Connection conn  = DButil.getConnection();
		try {
			PreparedStatement pstmt = conn.prepareStatement(LINKLIST);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				Link L = new Link();
				L.setId(rs.getInt("id"));
				L.setName(rs.getString("name"));
				L.setAddress(rs.getString("address"));
				L.setImg_logo(rs.getString("img_logo"));
				L.setSort(rs.getString("sort"));
				list.add(L);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public int addlink(Link L) {
		int i = 1,ret = 0;
		Connection conn = DButil.getConnection();
		
		try {
			PreparedStatement pstmt = conn.prepareStatement(ADDLINK);
			//pstmt.setInt(i++, L.getId());
			pstmt.setString(i++, L.getName());
			pstmt.setString(i++, L.getAddress());
			pstmt.setString(i++, L.getImg_logo());
			pstmt.setString(i++, L.getSort());
			ret = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			DButil.close();
		}
		return ret;
	}

	public int dellink(Integer id) {
		int i = 1,ret = 0;
		Connection conn = DButil.getConnection();
		try {
			boolean autoCommit = conn.getAutoCommit();
			conn.setAutoCommit(false);
			PreparedStatement pstmt = conn.prepareStatement(DELLINK);
			pstmt.setInt(1, id);
			ret = pstmt.executeUpdate();//按id删除
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DButil.close();
		}
		return ret;
	}

	public int editlink(Link L) {
		int i = 1,ret = 0;
		try {
			PreparedStatement pstmt = DButil.getPreparedStatement(EDITLINK);
			pstmt.setString(i++, L.getName());
			pstmt.setString(i++, L.getAddress());
			pstmt.setString(i++, L.getSort());
			pstmt.setInt(i++, L.getId());
			ret = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			DButil.close();
		}
		return ret;
	}

	}

